Back
Templating
By Monkeymatt last edited on Saturday, May 20, 2006 at 1:11:02 pm by Monkeymatt. Page
6.
Now we get to add some functions that help usability. Here we have an update to the
__set() function that allow us to change variables in the file as a whole, and in specific sections, depending on how we call it.
PHP Code
<?php
// Replaces references using __set special method (setting a variable calls this if the variable is not accessible to them)
// e.x. $template->java="fun"; -- $name=java, $value=fun
public function __set($name, $value) {
if (strpos($name, "base_") === 0) { // starts with 'base_', do whole section
$name=substr($name, 5); // remove 'base_' from the beginning
$this->level_tracker[0]['****code****']=str_replace("{".$name."}", $value, $this->level_tracker[0]['****code****']);
} else {
if ($this->current_level < 1) {
$this->error("value set", "No Section Set (Use 'base_' before the term to do it in the whole of the file)");
}
$num=$this->current_item['****current_iteration****']; // for below
if (empty($this->current_item[$num]['****code****'])) { // no code for current_item, so set it
$this->current_item[$num]['****code****']=$this->current_item['****code****'];
}
$this->current_item[$num]['****code****']=str_replace("{".$name."}", $value, $this->current_item[$num]['****code****']);
}
}
?>
Here we updated the
__set() function to have multiple cases. We have here where we can precede a variable name with
base_, and it will do it in the whole template file, but if we call it without the
base_, then we only replace it in the section we are working on.
Here is the function to allow us to use sections as loops (advance the loop):
PHP Code
<?php
// Go to next section iteration
public function next_section_iteration() {
$num=$this->current_item['****current_iteration****']; // get current number
if (empty($this->current_item[$num]['****code****'])) { // fill up current iteration if empty
$this->current_item[$num]['****code****']=$this->current_item['****code****'];
}
$this->current_item['****current_iteration****']++; // increase number
}
?>
Here we grab the current number, and fill up that iteration if still empty (if you just want to say something several times). Then we just increment the number of the current iteration for next time we set variables.
Next we can finally start the output.